package me.zhengjie.modules.sync;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.service.property.domain.SyncDataErrorLog;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import com.qiaofang.applet.service.property.service.SyncDataLogService;
import com.qiaofang.applet.service.property.service.SyncDataQueueService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import me.zhengjie.modules.sync.request.MiniProgramSynchronousRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.Optional;

import static me.zhengjie.modules.quartz.service.constants.SyncConstants.ON;
import static me.zhengjie.modules.quartz.service.constants.SyncConstants.UN_HANDLE;

@Slf4j
@Service
public class DataErrorPullService {
    private RestTemplate template;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);
        requestFactory.setReadTimeout(30000);
        template = new RestTemplate(requestFactory);
    }

    protected SyncCommon syncCommon;

    @Autowired
    SyncDataQueueService syncDataQueueService;

    @Autowired
    SyncDataLogService syncDataLogService;

    public Boolean pullSyncByDataErrorLog(SyncDataErrorLog syncDataErrorLog){
        try {
            SyncCommon syncCommonObject = JSON.parseObject(syncDataErrorLog.getSyncCommon(), SyncCommon.class);
            MiniProgramSynchronousRequest request = JSON.parseObject(syncDataErrorLog.getRequestBody(), MiniProgramSynchronousRequest.class);
            this.syncCommon = syncCommonObject;
            JSONObject firstRequest = httpRequest(request, syncDataErrorLog.getUrl());
            if (null == firstRequest) {
                log.info("request result is null");
                syncDataErrorLog.setRetry(false);
                syncDataLogService.save(syncDataErrorLog);
                return false;
            }
            JSONArray data = firstRequest.getJSONArray("data");
            //兼容视频 VR
            if (null == data) {
                data = firstRequest.getJSONArray("list");
            }
            if(save(data, syncDataErrorLog.getDataType())){
                syncDataLogService.deleteById(syncDataErrorLog.getId());
            }else {
                syncDataErrorLog.setRetry(false);
                syncDataLogService.save(syncDataErrorLog);
            }
        } catch (Exception e) {
            syncDataErrorLog.setRetry(false);
            syncDataLogService.save(syncDataErrorLog);
            log.error("pull prams {},error {}", JSON.toJSONString(syncCommon), e);
            return false;
        }
        return true;
    }

    public Boolean pullSyncDataErrorLogById(String id) {
        Optional<SyncDataErrorLog> optional = syncDataLogService.findById(id);
        SyncDataErrorLog syncDataErrorLog = optional.get();
        if (null == syncDataErrorLog) {
            return false;
        }
        return pullSyncByDataErrorLog(syncDataErrorLog);
    }

    public Boolean save(JSONArray data, String dataType) {
        if (null == data || data.size() <= 0) {
            log.info("data is null");
            return false;
        }
        //保存到中间表
        SyncDataQueue dataQueue = new SyncDataQueue();
        dataQueue.setBatchContent(data.toJSONString());
        dataQueue.setDataType(dataType);
        dataQueue.setProcessingStatus(UN_HANDLE);
        dataQueue.setCorporationCode(syncCommon.getCorporationCode());
        dataQueue.setCityCode(syncCommon.getCityCode());
        dataQueue.setCompanyUuid(syncCommon.getCompanyUuid());
        syncDataQueueService.save(dataQueue);
        return true;
    }


    private JSONObject httpRequest(Object object, String url) {
        HttpHeaders headers = getHeaders();
        log.info("sync params {},header {}", object, headers);
        String result = template.postForObject(url, new HttpEntity<>(object, headers), String.class);
        log.info("sync result {}", result);
        if (Objects.isNull(result)) {
            return null;
        }
        JSONObject resultObject = JSON.parseObject(result);
        if (null == resultObject) {
            return null;
        }
        String responseCode = resultObject.getString("responseCode");
        if (!ON.equals(responseCode)) {
            String responseMessage = resultObject.getString("responseMessage");
            log.info("sync error {}", responseMessage);
            return null;
        }
        return resultObject;
    }

    private HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", syncCommon.getAppId());
        headers.add("X-AUTH-KEY", syncCommon.getAppKey());
        headers.add("companyUuid", syncCommon.getCompanyUuid());
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }
}
